const db = require('../db/index')
const bcrypt = require('bcryptjs')
module.exports = {
  getUserInfo: (req, res) => {
    db.query(`select id,username,nickname,email,user_pic from ev_user where id=?`, req.auth.id, (err, result) => {
      if (err) return res.cc(err)
      if (result.length !== 1) return res.cc('获取用户信息失败')
      res.send({
        status: 0,
        message: '获取用户信息成功',
        data: result[0]
      })
    })
  },
  updateUserInfo: (req, res) => {
    db.query('update ev_user set ? where id=?', [req.body, req.body.id], (err, result) => {
      if (err) return res.cc(err)
      if (result.affectedRows !== 1) return res.cc('更新用户基本信息失败')
      res.cc('更新用户信息成功', 0)
    })
  },
  updatePassword: (req, res) => {
    db.query(`select * from ev_user where id=?`, req.auth.id, (err, result) => {
      if (err) return res.cc(err)
      if (result.length !== 1) return res.cc('用户不存在')
      if (!bcrypt.compareSync(req.body.oldPwd, result[0].password)) return res.cc('旧密码错误')
      const newPwd = bcrypt.hashSync(req.body.newPwd, 10)
      db.query(`update ev_user set password=? where id=?`, [newPwd, req.auth.id], (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('更新密码失败')
        res.cc('更新密码成功', 0)
      })

    })
  },
  updateAvanter: (req, res) => {
    db.query('update ev_user set user_pic=? where id=?', [req.body.avanter, req.auth.id], (err, result) => {
      if (err) return res.cc(err)
      if (result.affectedRows !== 1) return res.cc('更换头像失败')
      res.cc('更换头像成功',0)
    })
  }
}